package com.lagou.rocketmq.listener;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.entity.Order;
import com.lagou.rocketmq.service.OrderService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "place_order",
                        consumerGroup = "consumer_group_order",
                        consumeMode = ConsumeMode.CONCURRENTLY,
                        messageModel = MessageModel.CLUSTERING,
                        secretKey = "*")
public class OrderListener implements RocketMQListener<Order> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @SneakyThrows
    @Override
    public void onMessage(Order order) {
        Long orderId = orderService.addOrder(order.getProductId(), order.getUserId());
        order.setId(orderId);

        Message message = new Message("timeout_order", JSON.toJSONString(order).getBytes());
        org.springframework.messaging.Message springMsg = RocketMQUtil.convertToSpringMessage(message);

//        rocketMQTemplate.asyncSend(message.getTopic(), springMsg, new SendCallback() {
        rocketMQTemplate.asyncSend(message.getTopic(), MessageBuilder.withPayload(order).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable);
            }
        }, 10000, 3);

    }
}
